function logArray(message = '', array) {
  const output = `${message} => (${array.length}) [${array.join(',')}]`
  document.write(`<p>${output}</p>`)
  console.log(message.array)
}

let numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

console.log('原数组', numbers)

function printArray(myArray) {
  for (let i = 0; i < myArray.length; i++) {
    console.log(myArray[i])
  }
}

/**
 * --------------------------------------------------------------------------
 * 在数组末尾插入元素
 * --------------------------------------------------------------------------
 */

// 给数组添加一个新的元素
numbers[numbers.length] = 10
console.log('末尾插入10', numbers)

numbers.push(11)
console.log('末尾插入11', numbers)
numbers.push(12, 13)
console.log('末尾插入12, 13', numbers)

/**
 * --------------------------------------------------------------------------
 * 在数组开头插入元素
 * --------------------------------------------------------------------------
 */
Array.prototype.insertFirstPosition = function (value) {
  for (let i = this.length; i > 0; i--) {
    this[i] = this[i - 1]
  }
  this[0] = value
}

numbers.insertFirstPosition(-1)
console.log('开头插入-1', numbers)
// printArray(numbers)

// 使用 unshift 方法
numbers.unshift(-2)
console.log('开头插入-2', numbers)
// printArray(numbers)

numbers.unshift(-4, -3)
console.log('开头插入-4, -3', numbers)
// printArray(numbers)

/**
 * --------------------------------------------------------------------------
 * 删除元素
 * --------------------------------------------------------------------------
 */
numbers.pop()
console.log('从末尾删除元素通过pop方法', numbers)

for (let i = 0; i < numbers.length; i++) {
  numbers[i] = numbers[i + 1]
}

console.log('从开头删除元素', numbers)
console.log('删除后的数组长度', numbers.length)

// reset array
numbers = [-4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]

Array.prototype.reIndex = function (myArray) {
  const newArray = []
  for (let i = 0; i < myArray.length; i++) {
    if (myArray[i] !== undefined) {
      newArray.push(myArray[i])
    }
  }
  return newArray
}

// 手动移除第一个元素并重新排序
Array.prototype.removeFirstPosition = function () {
  for (let i = 0; i < this.length; i++) {
    this[i] = this[i + 1]
  }
  return this.reIndex(this)
}

numbers = numbers.removeFirstPosition()
console.log('Removed first with removeFirstPosition + reIndex', numbers)

// 使用 shift 方法
numbers.shift()
console.log('删除第一个元素', numbers)
console.log('删除第一个元素后的数组长度', numbers.length)

/**
 * --------------------------------------------------------------------------
 * 在任意位置添加或删除元素
 * --------------------------------------------------------------------------
 */
// splice 方法 - 参数(index, howManyPositionsToBeRemoved, item1...itemX)
numbers.splice(5, 3)
console.log('从索引为5开始移除3个元素(3, 4, 5)', numbers)

numbers.splice(5, 0, 2, 3, 4)
console.log('从索引为5开始添加3个元素(2, 3, 4)', numbers)

numbers.splice(5, 3, 2, 3, 4);
console.log('从索引为5开始移除3个元素(2, 3, 4)', numbers)
